<template>
  <div class="upload">
    <!-- 文件上传-组件 -->
    <el-upload
      :on-error="uploadError"
      :headers="headers"
      :before-upload="beforeFileload"
      :accept="accept"
      :on-success="uploadRes"
      class="uploadContent"
      :action="url"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      multiple
      :limit="limit"
      ref="uploadComponent"
      :on-exceed="handleExceed"
      :auto-upload="autoupload"
      :file-list="fileList"
      :data="uploadData"
      :on-change="fileStateChange"
    >
      <slot v-if="fileUrlArr.length<limit"></slot>
      <el-button size="small" v-if="showBtn" type="primary">添加图片</el-button>
    </el-upload>
  </div>
</template>

<script>

const baseURL = 'http://test.gateway.dzxz.com/GateWay';
const TOKEN_KEY = ''

export default {
  props: {
    showBtn:{
      type: Boolean,
      default: true
    },
    autoupload: {
      type: Boolean,
      default: true
    },
    uploadurl: {
      type: String,
      default: `${baseURL}/File/UploadFiles`
    },
    limit: {
      type: Number,
      default: 9
    },
    accept: {
      type: String,
      default: 'image/*,.doc,.docx,.txt'
    },
    // 是否拥有上传成功后的回调函数
    addCallback: {
      type: Boolean,
      default: false
    },
    // 上传时附带的额外参数
    uploadData: {
      type: Object,
      default: null
    },
    // 是否需要读取文件 用于excel读取
    needReadFile: {
      type: Boolean,
      default: false
    },
    headers:{
      type:Object,
      default:()=>({ Authorization:TOKEN_KEY })
    },
  },
  data() {
    return {
      url: this.uploadurl, // `${baseURL}/File/UploadFiles`,
      // 上传文件列表
      fileList: [],
      // 存路径数组
      fileUrlArr: [],
      sizeJudge: true,
      // headers: { Authorization:TOKEN_KEY }, // 上传文件请求头
      // 加载层
      loading: null,
      datas: [], // excel数据转化为json
      cols: []
    }
  },
  computed: {
    /* fileUrls() {
      let arr = this.fileUrlArr.map(item => {
        return item.FileUrl;
      });
      return arr;
    } */
  },
  watch: {
    datas(newVal) {
      if (newVal) {
        this.$emit('readFiles', newVal)
      }
    }
  },
  methods: {
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    fileStateChange(file, fileList) {
      
    },
    // 手动提交
    submitFile() {
      this.$refs.uploadComponent.submit()
    },
    // 清空文件列表
    clearFiles() {
      this.$refs.uploadComponent.clearFiles()
    },
    beforeFileload(file) {
      if (this.addCallback) {
        this.loading = this.$loading({ text: '上传中...' })
      }
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!')
        this.sizeJudge = false
      } else {
        this.sizeJudge = true
      }
      return isLt1M
    },
    /**
     * 文件列表移除文件时的钩子
     * @param {object} file 当前文件
     * @param {array} fileList 上传的文件列表
     */
    handleRemove(file, fileList) {
      // 删除文件同时移除上传的url
      this.fileUrlArr = this.fileUrlArr.filter(
        item => item !== file.response.data[0].FileUrl
      )
      this.$emit('readFiles', [])
    },
    //   点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      // console.log(file);
    },
    //   文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，共选择了 ${files.length +
          fileList.length} 个文件`
      )
    },
    //   删除文件之前的钩子
    beforeRemove(file, fileList) {
      if (this.sizeJudge) {
        return this.$confirm(`确定移除 ${file.name}？`)
      }
    },
    // 上传成功时的钩子
    uploadRes(response, file, fileList) {
      if (response.success||response.isSucceed) {
        // 上传成功后 后台返回一个路径
        this.loading.close()
        this.fileUrlArr.push(response.data[0].FileUrl)
        if (this.addCallback) {
          this.$emit('uploadSuccess', response)
        }
      } else {
        if (this.addCallback) {
          this.loading.close()
        }
        this.$message.error(response.msg)
      }
    },
    uploadError(err, file, fileList) {
      if (this.addCallback) {
        this.loading.close()
      }
      this.$message.error(err)
    }
  }
}
</script>

<style lang="less">
.upload {
  .el-upload-list {
    display: inline-block;
    margin: 5px 0 0 5px;
    vertical-align: middle;
    .el-upload-list__item {
      float: left;
      width: 150px;
      line-height: 32px;
      margin: 0;
      .el-icon-close {
        top: 10px;
      }
      .el-icon-close-tip {
        top: 10px;
        display: none;
      }
    }
  }
}
</style>
